<template>
  <div class="select">
    <van-field
      :label="payload.label"
      :name="payload.key"
      readonly
      is-link
      :required="payload.required"
      :rules="payload.rules"
      placeholder="请选择"
      @click="showPicker"
    >
      <template #input>
        <van-tag
          plain
          round
          size="medium"
          type="primary"
          v-for="tag in payload.dataList"
          :key="tag"
          class="mr6 mb4"
        >
          {{ tag }}
        </van-tag>
      </template>
    </van-field>
    <van-popup v-model="pickerShow" title="请选择" position="bottom" round>
      <!-- 标签需要多选,vant没有提供,只能自己写 -->
      <div class="popup">
        <div class="flex-between-center btns">
          <a class="info" @click="onCancel">取消</a>
          <a class="primary" @click="onConfirm">确认</a>
        </div>
        <van-checkbox-group v-model="value[payload.key]">
          <van-cell
            v-for="item in columns"
            :key="item[payload.valueKey]"
            class="flex-center-center flex-start checkbox-item"
          >
            <van-checkbox
              :name="item[payload.valueKey]"
              :value="(value[payload.key] || []).includes(item[payload.valueKey])"
            >
              {{ item[payload.labelKey] }}
            </van-checkbox>
          </van-cell>
        </van-checkbox-group>
      </div>
    </van-popup>
  </div>
</template>

<script>
export default {
  name: 'CMultipleSelect',
  props: {
    payload: {
      type: Object,
      default: () => ({
        dataList: [], // 需要显示的数据,[string]
        columns: [], // 整个列表数据,[{}]
        label: '',
        labelKey: '',
        valueKey: '',
        key: '', // 字段名
        required: false,
        rules: [],
      }),
    },
    value: Object,
  },
  data() {
    return {
      pickerShow: false,
    };
  },
  computed: {
    columns() {
      return this.payload.columns;
    },
  },
  methods: {
    showPicker() {
      this.pickerShow = true;
    },
    // 取消时将选中的清空
    onCancel() {
      const { key } = this.payload;
      this.$emit('input', {
        ...this.value,
        [key]: [],
      });
      this.pickerShow = false;
    },
    onConfirm() {
      const { key } = this.payload;
      this.$emit('input', {
        ...this.value,
        [key]: this.value[key],
      });
      this.$emit('change');
      this.pickerShow = false;
    },
  },
};
</script>

<style lang="less" scoped>
.popup {
  padding-top: 12px;
  padding-bottom: 24px;
  .btns {
    padding: 4px 16px;
    margin-bottom: 36px;
  }
  .checkbox-item {
    padding: 12px;
  }
}
</style>
